package cn.zhizihua.service.impl;

import cn.zhizihua.exception.AppException;
import cn.zhizihua.exception.AppExceptionCodeMsg;
import cn.zhizihua.mapper.OrderDetailMapper;
import cn.zhizihua.mapper.OrderMapper;
import cn.zhizihua.pojo.Order;
import cn.zhizihua.pojo.OrderDetail;
import cn.zhizihua.query.BaseQuery;
import cn.zhizihua.query.OrderQuery;
import cn.zhizihua.service.IOrderService;
import cn.zhizihua.vo.PageBean;
import cn.zhizihua.vo.ResultBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  1、添加@Service 注解
 *  2、装配Mapper层对象
 *  3、进行方法参数校验  事务处理@Transactional
 */
@Service
public class OrderService implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     *
     * @param order  如果参数值传递一个order对象  那么订单详情的集合就需要放在Order身上
     * @return
     */
    @Transactional
    @Override
    public ResultBean add(Order order) {
        // 参数校验
        if (order==null ||
                order.getUserId()==null || order.getUserId()==0 ||
                order.getBusinessId()==null || order.getBusinessId()==0 ||
                order.getAddressId()==null || order.getAddressId()==0){
            // 请求参数为空
            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
        }

        order.setOrderDate(new Date()); //设置下单时间为当前日期时间
        order.setOrderState(0); //设置未支付的订单状态

        //使用uuid（Universally Unique Identifier）生成订单编号
        order.setOrderNumber(UUID.randomUUID().toString().replaceAll("-",""));

        //判断是否存在总价  不存在就计算并设置
        if(order.getOrderTotal()==null){
            //遍历订单详情
            List<OrderDetail> orderDetailList = order.getOrderDetailList();
            double allPrice = 0;
            for (OrderDetail detail:orderDetailList) {
                allPrice += detail.getFood().getFoodPrice()*detail.getQuantity();
            }
            order.setOrderTotal(allPrice);
        }

        int add = orderMapper.add(order);

        //订单添加成功
        if (add>0){

            //循环将订单编号设置给每一个订单详情对象
            List<OrderDetail> orderDetailList = order.getOrderDetailList();
            for (OrderDetail detail:orderDetailList) {
                detail.setOrderId(order.getOrderId());
            }
            //批量添加订单详情
            int i = orderDetailMapper.addBatch(order.getOrderDetailList());
            //判断订单详情是否添加成功
            if (i==order.getOrderDetailList().size()){
                return ResultBean.SUCCESS();
            }
        }

        return ResultBean.ERROR("orderService-add 添加订单失败");
    }

    @Transactional
    @Override
    public ResultBean update(Order order) {
        // 参数校验
        if (order==null ||
                order.getOrderId()==null || order.getOrderId()==0 ||
                order.getUserId()==null || order.getUserId()==0 ||
                order.getBusinessId()==null || order.getBusinessId()==0 ||
                order.getAddressId()==null || order.getAddressId()==0  ||
                order.getOrderDate()==null ||
                order.getOrderTotal()==null || order.getOrderTotal()==0
        ){
            return ResultBean.ERROR("orderService-update 请求参数为空");
        }
        int i = orderMapper.update(order);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("orderService-update 修改订单失败");
    }

    /**
     * 删除订单时  同时删除关联的订单详情
     * @param id  订单编号  orderId
     * @return
     */
    @Transactional
    @Override
    public ResultBean delete(Integer id) {
        // 参数校验
        if (id == null){
            return ResultBean.ERROR(10001,"orderService-delete 请求参数为空");
        }

        //删除订单信息
        int delete = orderMapper.delete(id);
        if (delete==0){
            throw new RuntimeException("删除订单失败"+id);
        }

        //同时关联删除订单详情
        int i = orderDetailMapper.deleteByOrderId(id);
        if (i==0){
            throw new RuntimeException("删除订单详情失败"+id);
        }

        return ResultBean.SUCCESS();
    }

    @Transactional(readOnly = true)
    @Override
    public ResultBean getById(Integer id) {
        // 参数校验
        if (id == null){
            return ResultBean.ERROR("orderService-getById 请求参数为空");
        }
        Order byId = orderMapper.getById(id);
        return byId!=null?ResultBean.SUCCESS(byId):ResultBean.ERROR("orderService-getById 根据id查询订单失败");
    }

    @Override
    public ResultBean getAll(OrderQuery orderQuery) {
        //参数校验
        if (orderQuery == null){
            throw new AppException(AppExceptionCodeMsg.PARAMS_EMPTY);
        }

        //使用分页插件
        Page<Order> page = PageHelper.startPage(orderQuery.getPageNow(), orderQuery.getPageCount());

        //查询全部数据 & 设置分页条件 & orderQuery携带搜索信息
        List<Order> list = orderMapper.getAll(orderQuery);

        PageBean<Order> pageBean = new PageBean<>();
        pageBean.setTotalRows(page.getTotal());
        pageBean.setData(list);
        return ResultBean.SUCCESS(pageBean);
    }


    /**
     * 批量删除订单
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public ResultBean batchDel(List<Integer> ids){
        if (ids==null || ids.size()==0){
            return ResultBean.ERROR("orderService-batchDel 批量删除ids为空");
        }

        for (Integer id:ids){
            //删除订单
            int delete = orderMapper.delete(id);
            if (delete < 1){
                throw new RuntimeException("orderService-batchDel 批量删除订单失败");
            }
            //同时关联删除订单详情
            int i = orderDetailMapper.deleteByOrderId(id);
            if (i==0){
                throw new RuntimeException("删除订单详情失败"+id);
            }
        }

        return ResultBean.SUCCESS();
    }

    /**
     * 根据订单编号查询对应的订单详情
     * @param orderId
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public ResultBean getDetailsByOrderId(Integer orderId) {
        if (orderId==null || orderId==0){
            return ResultBean.ERROR("参数为空");
        }
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
        return ResultBean.SUCCESS(orderDetails);
    }

    @Override
    public ResultBean getOrderByUserId(Integer userId) {

        if (userId==null || userId==0){
            return ResultBean.ERROR("参数为空");
        }

        List<Order> orderList = orderMapper.getOrderByUserId(userId);

        return ResultBean.SUCCESS(orderList);
    }
}
